// src/api/weatherApiService.ts
import axios from 'axios';
import type { AxiosResponse } from 'axios';
import { ElMessage } from 'element-plus';

// 数据类型定义
export interface WeatherData {
    id: number;
    record_date: string;
    guilin_temp: number;
    guilin_max: number;
    guilin_min: number;
    guilin_dewp: number;
    guilin_mxspd: number;
    guilin_prcp: number;
    guilin_slp: number;
    guilin_visib: number;
    guilin_wdsp: number;
    hezhou_max: number;
    hezhou_min: number;
    liuzhou_max: number;
    liuzhou_min: number;
}

interface Pagination {
    page: number;
    page_size: number;
    total_pages: number;
    total_count: number;
}

interface ApiResponse {
    code: number;
    message: string;
    data: WeatherData[];
    pagination: Pagination;
}

interface YearsResponse {
    code: number;
    message: string;
    data: number[];
}

const API_BASE_URL = 'http://127.0.0.1:5000'; // 根据实际后端地址调整

const service = axios.create({
    baseURL: API_BASE_URL,
    timeout: 10000,
});

// 请求拦截器
service.interceptors.request.use(config => {
    config.paramsSerializer = {
        indexes: null // 解决数组参数序列化问题
    };
    return config;
});

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        const res = response.data;
        if (res.code !== 200) {
            ElMessage.error(res.message || '请求失败');
            return Promise.reject(new Error(res.message || 'Error'));
        }
        return res;
    },
    (error) => {
        let message = '请求失败';
        if (error.response) {
            switch (error.response.status) {
                case 400:
                    message = '参数错误';
                    break;
                case 404:
                    message = '接口不存在';
                    break;
                case 500:
                    message = '服务器错误';
                    break;
            }
        }
        ElMessage.error(`${message}: ${error.message}`);
        return Promise.reject(error);
    }
);

export const WeatherApiService = {
    /**
     * 获取所有可用年份
     */
    async getAvailableYears(): Promise<number[]> {
        try {
            const response: YearsResponse = await service.get('/api/get_available_years');
            return response.data || [];
        } catch (error) {
            console.error('获取年份列表失败:', error);
            ElMessage.error('获取年份列表失败');
            return [];
        }
    },

    /**
     * 获取全部历史数据
     * @param params 查询参数
     */
    async getAllData(params?: {
        page?: number;
        page_size?: number;
        fields?: string[];
    }): Promise<ApiResponse> {
        try {
            const response = await service.get('/api/get_historical_data_all', {
                params: {
                    ...params,
                    fields: params?.fields?.join(',')
                }
            });
            return response;
        } catch (error) {
            console.error('获取全部数据失败:', error);
            throw error;
        }
    },

    /**
     * 按年份查询数据
     * @param params 查询参数
     */
    async getDataByYear(params: {
        year: string;
        page?: number;
        page_size?: number;
        fields?: string[];
    }): Promise<ApiResponse> {
        try {
            const response = await service.get('/api/get_historical_data_by_year', {
                params: {
                    ...params,
                    fields: params.fields?.join(',')
                }
            });
            return response;
        } catch (error) {
            console.error('按年份查询失败:', error);
            throw error;
        }
    },

    /**
     * 按年月查询数据
     * @param params 查询参数
     */
    async getDataByYearMonth(params: {
        year: string;
        month: string;
        page?: number;
        page_size?: number;
        fields?: string[];
    }): Promise<ApiResponse> {
        try {
            const response = await service.get('/api/get_historical_data_by_year_and_month', {
                params: {
                    ...params,
                    fields: params.fields?.join(',')
                }
            });
            return response;
        } catch (error) {
            console.error('按年月查询失败:', error);
            throw error;
        }
    },

    /**
     * 获取指定城市温度数据
     * @param year 年份
     * @param city 城市 (guilin/hezhou/liuzhou)
     */
    async getCityTemperatureData(
        year: string,
        city: 'guilin' | 'hezhou' | 'liuzhou'
    ): Promise<ApiResponse> {
        try {
            return this.getDataByYear({
                year,
                fields: ['record_date', `${city}_max`, `${city}_min`],
                page_size: 365
            });
        } catch (error) {
            console.error('获取城市温度数据失败:', error);
            throw error;
        }
    }
};

// 使用示例：
// 1. 获取年份列表
// WeatherApiService.getAvailableYears().then(years => console.log(years))
//
// 2. 获取2023年数据
// WeatherApiService.getDataByYear({ year: '2023', page: 1, page_size: 20 })
//
// 3. 获取桂林市温度数据
// WeatherApiService.getCityTemperatureData('2023', 'guilin')